<template>
    <page-meta :page-style="$theme.pageStyle">
        <!-- #ifndef H5 -->
        <navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor" />
        <!-- #endif -->
    </page-meta>
    <view class="index" :style="pageStyle">
        <!-- 组件 -->
        <template v-for="(item, index) in state.pages" :key="index">
            <template v-if="item.name == 'banner'">
                <u-navbar
                    :title="state.meta[0].content.title"
                    :is-fixed="false"
                    :is-back="false"
                    :border-bottom="false"
                    :background="{ background: 'rgba(256,256, 256,' + percent + ')' }"
                    :title-color="'#000'"
                >
                </u-navbar>
                <w-banner
                    :content="item.content"
                    :styles="item.styles"
                    :isLargeScreen="isLargeScreen"
                    @change="handleBanner"
                    class="banner-margin-top"
                />
            </template>
        </template>
        <!-- 新增：出行表单 -->
        <view class="trip-form">
            <!-- 上车地点 -->
            <view class="form-group" style="margin-left: 30rpx">
                <text class="dot">●</text>
                <text class="label" style="margin-right: 10rpx">您将从</text>
                <input
                    style="width: 240rpx"
                    class="input"
                    :value="startLocation"
                    placeholder="您将从"
                    @tap="chooseStartLocation"
                    disabled
                />
                <u-icon name="arrow-right" @click="getLocation" size="20" color="#999" />
            </view>

            <!-- 目的地 -->
            <view class="form-group destination">
                <!-- 输入框与添加按钮在一行 -->

                <view class="destination-left">
                    <text class="dot to-dot">●</text>
                    <!-- 目的地输入框 -->
                    <input
                        class="input"
                        v-model="endLocation"
                        placeholder="您想去哪儿？"
                        @tap="chooseEndLocation"
                    />
                </view>

                <!-- 添加按钮（靠右） -->
                <view class="destination-right" @click="addWaypoint">
                    <view class="icon-text-container">
                        <u-icon name="search" size="24" color="#07c160" />
                        <text class="add-text">途经点</text>
                    </view>
                </view>
            </view>
            <!-- 途经点输入框列表 -->
            <view class="waypoint-list">
                <view class="waypoint-item">
                    <view v-for="(point, index) in waypoints" :key="index" class="input-wrapper">
                        <input
                            class="input waypoint-input"
                            v-model="point.name"
                            :placeholder="`途经点 ${index + 1}`"
                            @click="chooseWaypointsLocation"
                        />
                        <u-icon
                            name="close-circle"
                            class="remove-btn"
                            @click="removeWaypoint(index)"
                            size="24"
                            color="#f00"
                        />
                    </view>
                </view>
            </view>
            <!-- 提交按钮 -->
            <button class="submit-btn commit_btn" @click="goToSelectCar">立即选车</button>
        </view>
        <!-- 标签选择 -->
        <view class="route-tabs">
            <text
                v-for="(tab, index) in tabs"
                :key="index"
                :class="['tab-item', { active: activeTab === tab.name }]"
                @click="switchTab(tab.name)"
                >{{ tab.name }}
            </text>
        </view>
        <!-- 线路列表（图文） -->
        <view class="route-list">
            <u-row gutter="20" v-if="routes.length">
                <u-col :span="6" v-for="route in routes" :key="route.id">
                    <view class="route-item" @click="goToRouteDetail(route.id)">
                        <image :src="route.line_image" class="route-image" mode="aspectFill" />
                        <view class="route-info">
                            <text class="route-title">{{ route.title }}</text>
                            <view class="tags_view">
                                <view class="route-tags" v-if="route.tags && route.tags.length > 0">
                                    <text v-for="tag in route.tags" :key="tag" class="route-tag"
                                        >{{ tag }}
                                    </text>
                                </view>
                            </view>
                            <view class="route-desc">
                                <text class="price-value">￥{{ route.price }}</text>
                                <text class="price-unit">起/人</text>
                            </view>
                        </view>
                    </view>
                </u-col>
            </u-row>
        </view>
        <!-- 返回顶部按钮 -->
        <u-back-top
            :scroll-top="scrollTop"
            :top="100"
            :customStyle="{
                backgroundColor: '#FFF',
                color: '#000',
                boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
            }"
        >
        </u-back-top>

        <!--  #ifdef MP  -->
        <!--  微信小程序隐私弹窗  -->
        <MpPrivacyPopup></MpPrivacyPopup>
        <!--  #endif  -->

        <tabbar />
    </view>
</template>

<script setup lang="ts">
import { getIndex } from '@/api/shop'
import { onLoad, onPageScroll } from '@dcloudio/uni-app'
import { computed, reactive, ref } from 'vue'

import { getHotSearch } from '@/api/tags'
import { getLineList } from '@/api/lines'
// #ifdef MP
import MpPrivacyPopup from './component/mp-privacy-popup.vue'
// #endif

const state = reactive<{
    pages: any[]
    meta: any[]
    article: any[]
    bannerImage: string
}>({
    pages: [],
    meta: [],
    article: [],
    bannerImage: ''
})
const scrollTop = ref<number>(0)
const percent = ref<number>(0)

const startLocation = ref('西安人才中心')
const endLocation = ref('西安北客站')
const waypoints = ref<{ name: string }[]>([])

// 是否联动背景图
const isLinkage = computed(() => {
    return state.pages.find((item: any) => item.name === 'banner')?.content.bg_style === 1
})
// 是否大屏banner
const isLargeScreen = computed(() => {
    return state.pages.find((item: any) => item.name === 'banner')?.content.style === 2
})

// 根页面样式
const pageStyle = computed(() => {
    const { bg_type, bg_color, bg_image } = state.meta[0]?.content ?? {}
    if (!isLinkage.value) {
        return bg_type == 1
            ? { 'background-color': bg_color }
            : {
                  'background-image': `url(${bg_image})`
              }
    } else
        return {
            'background-image': `url(${state.bannerImage})`
        }
})

const handleBanner = (url: string) => {
    state.bannerImage = url
}

// 获取当前位置
const getLocation = () => {
    uni.showLoading({
        title: '定位中...',
        mask: true
    })
    uni.getLocation({
        type: 'wgs84',
        success: (res) => {
            startLocation.value = `经纬度(${res.latitude}, ${res.longitude})`
        },
        fail: () => {
            uni.showToast({ title: '定位失败', icon: 'none' })
        }
    })
}

// 地图选择上车点
const chooseStartLocation = () => {
    uni.chooseLocation({
        success: (res) => {
            startLocation.value = res.address + res.name
        }
    })
}

// 地图选择终点
const chooseEndLocation = () => {
    uni.chooseLocation({
        success: (res) => {
            endLocation.value = res.address + res.name
        }
    })
}

const chooseWaypointsLocation = () => {
    uni.chooseLocation({
        success: (res) => {
            waypoints.value.push({ name: res.address + res.name })
        }
    })
}

// 添加途经点
const addWaypoint = () => {
    waypoints.value.push({ name: '' })
}
// 添加删除方法
const removeWaypoint = (index: number) => {
    waypoints.value.splice(index, 1)
}
// 立即选车跳转
const goToSelectCar = () => {
    uni.navigateTo({
        url: `/pages/select_car/select_car?start=${encodeURIComponent(
            startLocation.value
        )}&end=${encodeURIComponent(endLocation.value)}&waypoints=${encodeURIComponent(
            JSON.stringify(waypoints.value)
        )}`
    })
}

const getData = async () => {
    const data = await getIndex()
    state.pages = JSON.parse(data?.page?.data)
    state.meta = JSON.parse(data?.page?.meta)
    state.article = data.article
    uni.setNavigationBarTitle({
        title: state.meta[0].content.title
    })
}
const activeTab = ref('')
// 标签数据
const tabs = ref<any[]>([])

const getTabs = async () => {
    try {
        const data = await getHotSearch()
        tabs.value = data.data
        if (tabs.value.length > 0) {
            activeTab.value = tabs.value[0].name // 设置默认选中第一个标签
            await getLines() // 立即加载线路数据
        }
    } catch (error) {
        console.error('获取标签数据失败:', error)
        // 可选：提示用户或进行其他错误处理
    }
}

// 路线数据（可从接口获取）
const routes = ref<any[]>([])

const getLines = async () => {
    try {
        const data = await getLineList({
            page_no: 1,
            page_size: 10,
            keyword: activeTab.value // 使用当前选中标签名称作为搜索词
        })
        const data_list = data.lists || []
        data_list.forEach((item: any) => {
            if (item.tags != '' && item.tags != null) {
                item.tags = item.tags.split(',')
            }
        })
        routes.value = data_list
    } catch (error) {
        console.error('获取路线数据失败:', error)
        routes.value = []
    }
}

// 切换标签
const switchTab = async (tabName: string) => {
    activeTab.value = tabName
    await getLines() // 切换标签时重新加载线路
}

const goToRouteDetail = (routeId: number) => {
    uni.navigateTo({
        url: `/pages/line_detail/line_detail?id=${routeId}`
    })
}

onPageScroll((event: any) => {
    scrollTop.value = event.scrollTop
    const top = uni.upx2px(100)
    percent.value = event.scrollTop / top > 1 ? 1 : event.scrollTop / top
})

onLoad(() => {
    getData()
    getTabs()
})
</script>

<style lang="scss" scoped>
.index {
    position: relative;
    background-repeat: no-repeat;
    background-size: 100% auto;
    overflow: hidden;
    width: 100%;
    transition: all 1s;
    min-height: calc(100vh - env(safe-area-inset-bottom));
}

.article-title {
    &::before {
        content: '';
        width: 8rpx;
        height: 34rpx;
        display: block;
        margin-right: 10rpx;
        @apply bg-primary;
    }
}

.trip-form {
    position: relative;
    border-radius: 24rpx;
    margin: -110rpx 20rpx 0;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    overflow: hidden;
    z-index: 99;
}

.form-group {
    display: flex;
    flex-direction: row; /* 改为水平排列 */
    align-items: center; /* 垂直居中对齐 */

    .dot {
        font-size: 16rpx;
        color: #999;
        margin-right: 12rpx;
    }

    .to-dot {
        color: #f9b961;
    }

    .label {
        font-size: 28rpx;
        color: #999;
        white-space: nowrap;
        text-align: left; // 左对齐
    }

    .input {
        font-size: 28rpx;
        color: #999;
        //flex: 2; /* 占据剩余空间 */
        padding: 30rpx 0;
        text-align: left;
        min-width: 0;
    }

    &.destination,
    &.waypoint-group {
        padding: 20rpx 10rpx;
    }

    .destination-row {
        display: flex;
        justify-content: space-between; // 左右对齐
        align-items: center;
        margin-bottom: 20rpx;
        padding: 0 10rpx;
    }

    .destination-left {
        flex: 1;
        min-width: 0;
        overflow: hidden;
        display: flex;
        align-items: center;
        background-color: #f9f9f9;
        border-radius: 16rpx;
        padding-left: 20rpx;
    }

    .destination-right {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx;
        border-radius: 12rpx;
        position: relative;
    }

    .icon-text-container {
        display: flex;
        flex-direction: column; /* 垂直排列 */
        align-items: center; /* 居中对齐 */
        justify-content: center; /* 垂直居中 */
    }

    .waypoint-item {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
    }

    .input-wrapper {
        display: flex;
        align-items: center; /* 垂直居中 */
        background-color: #f5f5f5; /* 输入框背景色 */
        border-radius: 8rpx; /* 圆角 */
        padding: 10rpx 20rpx; /* 内边距 */
        margin-bottom: 20rpx;

        .waypoint-input {
            flex: 1; /* 占据剩余空间 */
            font-size: 28rpx;
            color: #333;
            background-color: transparent; /* 透明背景以便看到外层背景 */
        }

        .remove-btn {
            margin-left: 10rpx; /* 图标与输入框文字间距 */
        }
    }

    .add-waypoint {
        width: 120rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        padding: 16rpx 0;
        color: #07c160;
        gap: 8rpx; // 图标与文字间距
    }

    .add-text {
        margin-top: 10rpx;
        font-size: 24rpx;
        line-height: 1;
        margin-left: 10rpx;
        //font-size: 28rpx;
    }

    .add-btn {
        margin-top: 20rpx;
        width: 100rpx;
        height: 60rpx;
        line-height: 60rpx;
        font-size: 40rpx;
        color: #07c160;
        background-color: #f0f8f4;
    }
}

.form-group.destination {
    display: flex;
}

.submit-btn {
    margin: 40rpx 10rpx;
}

.route-tabs {
    display: flex;
    overflow-x: auto; // 允许横向滚动
    white-space: nowrap; // 防止换行
    -webkit-overflow-scrolling: touch; // iOS 滚动优化
    padding: 20rpx 0;
    scrollbar-width: none; // 隐藏滚动条（可选）
    -ms-overflow-style: none; // 隐藏滚动条（可选）
    &::-webkit-scrollbar {
        display: none; // 隐藏浏览器滚动条（可选）
    }
}

.tab-item {
    flex-shrink: 0; // 防止标签被压缩
    font-size: 28rpx;
    color: #666;
    position: relative;
    padding: 10rpx 20rpx;

    &.active {
        color: #07c160;
        font-weight: bold;

        &:after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background-color: #07c160;
        }
    }
}

.route-list {
    padding: 20rpx;
    margin-bottom: 70rpx;
}

.route-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 30rpx;

    border-radius: 16rpx;
    overflow: hidden;
    background-color: #fff;
}

.route-image {
    width: 100%;
    height: 220rpx;
    border-radius: 16rpx;
    flex-shrink: 0;
    object-fit: cover; // 图片内容覆盖整个容器（可选）
}

.route-info {
    flex: 1;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.route-title {
    overflow: hidden;
    height: 80rpx;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
}

.route-desc {
    display: flex;
    align-items: baseline; // 基线对齐
    font-size: 30rpx;
    color: #f6a22d;
    margin-top: 10rpx;
}

.price-value {
    font-weight: bold;
}

.price-unit {
    font-size: 16rpx;
    font-weight: lighter;
    margin-left: 4rpx; // 微调间距
}

.tags_view {
    display: flex;
    height: 60rpx;
}

.route-tags {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto; // 允许横向滚动
    gap: 12rpx;
    margin: 10rpx 0;
    padding-right: 20rpx; // 防止内容贴边
    -webkit-overflow-scrolling: touch; // iOS 滚动优化
    white-space: nowrap; // 防止文字换行
    scrollbar-width: none; // 隐藏滚动条（可选）
    -ms-overflow-style: none; // 隐藏滚动条（可选
}

.route-tags::-webkit-scrollbar {
    display: none; // 隐藏浏览器滚动条
}

.route-tag {
    background-color: #fffbf6;
    flex-shrink: 0; // 防止标签被压缩
    border: 1rpx solid #fbdaab;
    color: #f6a22d;
    font-size: 20rpx;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
    max-width: 180rpx; // 控制最大宽度（可选）
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis; // 超出显示省略号
}

.waypoint-list {
    margin-top: 20rpx;
    padding: 0 20rpx;
    display: flex;
}

.waypoint-item {
    flex: 1;
}

.input-wrapper {
    display: flex;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 10rpx 20rpx;
    margin-bottom: 20rpx;
    justify-content: space-between;
}
</style>
